<?php
/**
 * MageWorx
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the MageWorx EULA that is bundled with
 * this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.mageworx.com/LICENSE-1.0.html
 *
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@mageworx.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade the extension
 * to newer versions in the future. If you wish to customize the extension
 * for your needs please refer to http://www.mageworx.com/ for more information
 * or send an email to sales@mageworx.com
 *
 * @category   MageWorx
 * @package    MageWorx_DeliveryZone
 * @copyright  Copyright (c) 2009 MageWorx (http://www.mageworx.com/)
 * @license    http://www.mageworx.com/LICENSE-1.0.html
 */

/**
 * Delivery Zone extension
 *
 * @category   MageWorx
 * @package    MageWorx_DeliveryZone
 * @author     MageWorx Dev Team <dev@mageworx.com>
 */

class MageWorx_DeliveryZone_Model_Zone extends Mage_Core_Model_Abstract
{
    const ZONE_TYPE_CATEGORY = 'C';
    const ZONE_TYPE_SHIPPINGMETHOD = 'S';

    protected $_type = null;

    public function _construct()
    {
        parent::_construct();
        $this->_init('deliveryzone/zone');
    }

    public function setType($type)
    {
        $this->_type = $type;
        $this->setData('type', $type);
        return $this;
    }

    protected function _getResource()
    {
        $resource = parent::_getResource();
        return $resource->setType($this->_type);
    }

    public function getByLocation(Varien_Object $location)
    {
        return $this->_getResource()->getByLocation($location);
    }

    public function getZoneIdsByLocation(Varien_Object $location)
    {
        return $this->_getResource()->getZoneIdsByLocation($location);
    }

    public function getProductIdsByLocation(Varien_Object $location)
    {
        $this->setType(self::ZONE_TYPE_CATEGORY);
        return $this->_getResource()->getProductIdsByLocation($location);
    }
    
    protected function _beforeSave()
    {
    	parent::_beforeSave();
    	$zoneCollection = Mage::getResourceModel('deliveryzone/zone_collection')->setType($this->_type)->addZoneTitleFilter($this->getData('title'))->load();
    	$zoneId = $this->getId();
    	$items = $zoneCollection->getItems();
    	if ($items)
    	{
	    	foreach($items as $zone)
	    	{
	    		if ($zone['zone_id'] <> $zoneId)
	    		{
	    		  throw new Exception(Mage::helper('deliveryzone')->__('Duplicate Title "%s"', $zone['title']));
	    		}
	    	}
    	}    	
    }
}